<?php
require_once 'Crypt/Crypt.php';
require_once BASEPATH . 'apps/account/models/Account.php';

class Site_Auth implements Zend_Auth_Adapter_Interface {
    private $_username = null;
    private $_password = null;

    public function __construct($username, $password) {
        $this->_username = Site_Filter::get($username, 'Username');
        $crypt = new Crypt(Crypt::MODE_BIN, $this->_username);
        $this->_password = sha1($crypt->encrypt($password));
    }

    public function authenticate() {
        $table = new Account();
        $account = $table->fetchRow($table->select()->where('username = ?',
            $this->_username)->limit(1));
        if ($account === null)
            return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
                $this->_username);
        if ($account->password != $this->_password)
            return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
                $this->_username);
        return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $this->_username);
    }

    static public function restrictedAccess() {
        if (!Zend_Auth::getInstance()->hasIdentity())
            die(header('location: /account/signin/error/restricted'));
    }
}
?>
